const Router = require('koa-router');
const router = new Router();
const SystemLog = require('../server/libs/SysLog/SystemLog');
const { verified } = require('../server/libs/Token');

router.all('*', async function (ctx, next) {
    try {
        let url = ctx.req._parsedUrl.pathname;
        if (url.substr(0, 4) === '/api') {//判断请求路径是api，如果不是说明请求有误
            url = url.substr(4);//去除请求路径中的api
            if (url === '/signIn' || url === '/mobile/signIn') {        //判断请求是否为登陆功能如果是跳转到登陆页面
                let signInAction = require(`../routes${url}`);
                await signInAction.apply(ctx, arguments);
            } else {                      //否则的话需要验证header中的权限
                if (url.includes("/pathDownload")) {
                    let middleware = require(`../routes${url}`);
                    await middleware.apply(ctx, arguments);
                } else {
                    let _token = ctx.header.authorization;//获取令牌
                    let checkTokenResult = verified(_token);//验证令牌
                    if (!checkTokenResult.success) {  //如果失败则返回失败结果
                        ctx.body = { success: false, message: checkTokenResult.message };
                        return;
                    }
                    let middleware = require(`../routes${url}`);
                    if (!ctx.request.fields['userId']) ctx.request.fields['userId'] = checkTokenResult.decoded.user_id;
                    if (!ctx.request.fields['userGroupId']) ctx.request.fields['userGroupId'] = checkTokenResult.decoded.group_id;
                    if (checkTokenResult.decoded.domain_id) ctx.request.fields['userDomainId'] = checkTokenResult.decoded.domain_id;
                    if (checkTokenResult.decoded.agent_id) ctx.request.fields['userAgentId'] = checkTokenResult.decoded.agent_id;
                    await middleware.apply(ctx, arguments);
                }
            }
        } else {
            ctx.body = { success: false, message: 'path id errror' };
        }
    } catch (err) {
        ctx.body = { success: false, message: err.message };
        SystemLog(err, ctx);
    }
});
module.exports = router;